package ck.android.englishschool.home;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import ck.android.englishschool.AppStatus;
import ck.android.englishschool.BaseFragment;
import ck.android.englishschool.R;
import ck.android.englishschool.thread.BaseThread.ThreadCallBack;
import ck.android.englishschool.thread.WordListThread;
import ck.android.englishschool.util.Const;

public class WordInputFragment extends BaseFragment implements ThreadCallBack, OnScrollListener{
	private View view;
	private HomeActivity am;
	private AppStatus myapp;
	private Context context;
	private ProgressDialog dialog;
	private ArrayList<Integer> selectedArr;
	private ListView listView;
	
	private TextView headerTitleText;
	private boolean pageState;
	
	private WordListThread wordListThread;
	private WordListAdapter wordListAdapter;
	
	private HashMap<String,String>	searchMap;
	private int mPageCnt;
	
	private int nTotCnt = 0;
	
	private final static int MSG_THREAD_COMPLETED = 0;
	private final static int MSG_THREAD_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		searchMap = new HashMap<String,String>();
		mPageCnt = 1;
		if (view != null) {
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null)
				parent.removeView(view);
		} else {
			view = inflater.inflate(R.layout.fragment_word, container, false);
			init();
		}

		return view;
		
	}
	
	public void init(){
		context = view.getContext();
		myapp = (AppStatus) context.getApplicationContext();
		
		headerTitleText = (TextView)view.findViewById(R.id.headerTitleText);
		
		headerTitleText.setText("Word");
		
		listView = (ListView)view.findViewById(R.id.word_list);
		listView.setOnScrollListener(this);
		wordListAdapter = new WordListAdapter();
		
		selectedArr = new ArrayList<Integer>();
		
		dataLoad();
	}
	
	public void dataLoad(){
		searchMap.put(Const.TARGET_PAGE, ""+mPageCnt);
		wordListThread = new WordListThread(context, this, searchMap);
		wordListThread.start();
	}
	
	@Override
	public void Onback() {
		// TODO Auto-generated method stub
	}
	
	class WordListAdapter extends BaseAdapter{
		
		CheckBox list_word_chk;
		TextView txt_seq, txt_title;
		LinearLayout list_word_layout;
		
		@Override
		public int getCount() {
			return myapp.getArrWordList().size();
		}

		@Override
		public Object getItem(int position) {
			return myapp.getArrWordList().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
				LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = layoutInflater.inflate(R.layout.list_word ,parent ,false);
			}
			
			list_word_layout = (LinearLayout)convertView.findViewById(R.id.list_word_layout);
			list_word_chk = (CheckBox)convertView.findViewById(R.id.list_word_chk);
			txt_seq = (TextView)convertView.findViewById(R.id.txt_seq);
			txt_title = (TextView)convertView.findViewById(R.id.txt_title);
			
			txt_seq.setText(myapp.getArrWordList().get(position).getMemSeq());
			txt_title.setText(myapp.getArrWordList().get(position).getTitle());
			
			
			if(selectedArr.contains(position)){
				list_word_chk.setChecked(true);
			}else{
				list_word_chk.setChecked(false);
			}
			
			list_word_chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					
					if(isChecked){
							selectedArr.add(position);	
					}else{
						if(selectedArr.contains(position)){                                               
							selectedArr.remove(selectedArr.indexOf(position));                                   
                        }
					}
				}
			});
			
			return convertView;
		}
		
	}
	
	@Override
	public void threadCompleted(boolean isNetWordConnected,
			Object result, String message) {
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}
		
		if(!isNetWordConnected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if((Boolean) result) {
			Message msg = handler.obtainMessage();
			msg.what = MSG_THREAD_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void threadError(String message) {
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_THREAD_ERROR;
		/*if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}*/
		handler.sendMessage(msg);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_THREAD_COMPLETED:
				wordListAdapter.notifyDataSetChanged();
				listView.setAdapter(wordListAdapter);	
				if(pageState) listView.setSelection(listView.getCount()- 17);
				pageState = false;
				break;

			case MSG_THREAD_ERROR:
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);
				break;

			default:
				break;
			}
		}
	};
	
	private void showDialogNo(String message) {
		dialog = new ProgressDialog(context);
		dialog.setMessage(message);
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		dialog.show();
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == SCROLL_STATE_IDLE) 
		{
			if(!pageState){
				if (listView.getLastVisiblePosition() >= listView.getCount()-1) 
				{
					if(nTotCnt - listView.getCount() > 0){
						pageState = true;
						mPageCnt ++;
						//searchList();
						//myapp.utilm.showToast(context, "다음페이지로  = " + listView.getCount());					
					}else{
						myapp.utilm.showToast(context, "다음페이지 없음 ");
					}
				}				
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		
	}

	
}

